<?php
namespace App\Libs\Views;
//require __DIR__ . '/../thirdparty/smarty/SmartyBC.class.php';
//require __DIR__ . '';

class Smarty extends View
{
    private $engine;
    public function __construct() {
        $this->engine = new SmartyEngine();
    }
    public function show($response) {
        if (is_array($response)) {
            $params = isset($response['params']) ? $response['params'] : array();
            $tpl = isset($response['tpl']) && isset($response['tpl']) ? trim($response['tpl']) : 'empty.tpl.html';
            $base = isset($response['base']) && isset($response['base']) ? trim($response['base']) : 'html/base/base.tpl.html';
        } else {
            $params = array();
            $tpl = 'empty.tpl.html';
            $base = 'html/base/base.tpl.html';
        }
        $this->engine->show($params, $tpl, $base);
    }

    public function fetch($response) {
        if (is_array($response)) {
            $params = isset($response['params']) ? $response['params'] : array();
            $tpl = isset($response['tpl']) && isset($response['tpl']) ? trim($response['tpl']) : 'empty.tpl.html';
        } else {
        }
        return $this->engine->nfetch($params, $tpl);
    }

    public static function view($params, $tpl, $base = '') {
        return array('params' => $params, 'tpl' => $tpl, 'base' => $base);
    }
}

class SmartyEngine extends \SmartyBC
{
    public function __construct() {
	    $this->left_delimiter  =  '{{';
	    $this->right_delimiter =  '}}';
    }
    
    public function show($params = array(), $tpl = '', $base = '') {
        $pageCode = $this->nfetch($params, $tpl);
        $this->assign('page_code', $pageCode);
        $baseTpl = __DIR__ . '/../../views/tpl/' . $base;
        if (!file_exists($baseTpl)) {
            $baseTpl = __DIR__ . '/../../views/tpl/html/base/base.tpl.html';
        }
        $this->display($baseTpl);       
    }

    public function nfetch($params = array(), $tpl = '') {
        $this->assign($params);
        return $this->fetch(__DIR__ . '/../../views/tpl/' . $tpl);
    }
}
